import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';

async function handler(req: NextRequest) {
    const { page = 1, pageSize = 10, categoryId, type } = await req.json();

    const where: any = {};

    if (type) {
        where.type = type;
    }

    if (categoryId) {
        where.categories = {
            some: {
                categoryId: categoryId,
            },
        };
    }

    const contents = await prisma.content.findMany({
        where,
        skip: (page - 1) * pageSize,
        take: pageSize,
        orderBy: {
            createdAt: 'desc',
        },
        include: {
            categories: {
                include: {
                    category: true,
                },
            },
            cover: true,
        },
    });

    const total = await prisma.content.count({ where });

    return {
        data: {
            list: contents,
            total,
        },
    };
}

export const POST = withMiddleware(handler, { beforeCallback: [authenticateRequest] });